<?php

namespace common\dao\dd;

/**
 * 字典基类
 *
 * @author peng.huang
 */
class DdDao extends \common\base\BaseDao {

    /**
     * 字典数据源
     *
     * @var array
     */
    protected $_data = array();

    /**
     * 保存类实例的静态成员变量
     * 
     * @var DataDAO 
     */
    protected static $_instance;

    /**
     * 单例方法,用于访问实例的公共的静态方法
     * 
     * @param string $db [数据库]
     * @return DataDAO
     */
    public static function getSingleton($db = NULL) {
        if (!(static::$_instance instanceof static)) {
            static::$_instance = new static($db);
        }

        return static::$_instance;
    }

    /**
     * 返回字典
     *
     * @param string $type [类型]        	      	
     * @param callable $callBack [回调函数]  
     * @param bool $isFlip [是否键与值交换]  	
     * @param string|int $code [代码]  	
     * @return mixed
     */
    protected function _getDD($type, $callBack = NULL, $isFlip = TRUE, $code = NULL) {
        if (empty($this->_data [$type])) {
            $isExists = FALSE;
            if (file_exists($path = DATA_PATH . 'dd' . DIRECTORY_SEPARATOR . $type . '.inc.php')) {
                $isExists = TRUE;
            } else {
                if (is_callable($callBack) && '' !== ( $rows = call_user_func($callBack))) {
                    $context = '<?php' . PHP_EOL;
                    $context .= 'return array (' . PHP_EOL;
                    $context .= $rows;
                    $context .= ');';

                    $fp = fopen($path, 'w'); // 写文件
                    fwrite($fp, $context);
                    fclose($fp);

                    $isExists = TRUE;
                }
            }

            $this->_data [$type] = TRUE === $isExists ? include $path : array();
        }

        $arr = $this->_data [$type];
        if (TRUE === $isFlip) {
            $arr = array_flip($arr);
        }

        if (is_string($code) || is_int($code)) {
            return isset($arr [$code]) ? $arr [$code] : '';
        }

        return $arr;
    }

}
